const router = require('koa-router')();  //注意：引入的方式
const db = require('../utils/database.js')
const jwt = require('jsonwebtoken')  //编码插件
const { token, key } = require('../config/secret') //编码解码

router.prefix('/user')

router.get('/', ctx => {
    ctx.body = "user--index";
})

//////////////////////////////////////////////////////
// 文件上传
const multer = require('@koa/multer') // 引入
//////////////////
// 单域单文件上传
const storage = multer.diskStorage({ // multer调用diskStorage可控制磁盘存储引擎
    // 配置上传的文件目录及文件名
    destination: function (req, file, cb) {
        cb(null, './public/upload')
    },
    filename: function (req, file, cb) {
        const ext = file.originalname.split('.').pop()
        const newName = 'qtj-' + Date.now() + '.' + ext
        cb(null, newName) // 文件名使用cb回调更改，参数二是文件名，为了保证命名不重复，使用时间戳
    }
})
const upload = multer({ storage }) // 加载multer
router.post('/upload', upload.single('icon'), ctx => {
    // console.log(ctx.file);
    ctx.body = { success: true, code: 20000, message: "文件上传成功", data: ctx.file.filename } // 返回值是ctx.file.filename
})
////////////////////////////////////////////////////////

// 登录
//第一步获取令牌
router.post('/user-token', async ctx => {
    const { loginName, loginKey } = ctx.request.body
    const data = await db.findOne('user', { loginName, loginKey })
    // console.log(data);
    if (data.length == 0) {
        ctx.body = { success: false, errorCode: 41003, message: "用户名或密码错误", data: null }
    } else {
        const { _id, status } = data[0]
        if (status == 1) {
            ctx.body = { success: true, code: 20000, message: "登录成功", data: { token: token(_id) } }
        } else {
            ctx.body = { success: false, errorCode: 40000, message: "用户审核未通过", data: null }
        }
    }
})

//第二步获取用户信息
////根据token获取用户信息
router.get('/user-info', async ctx => {
    const { token } = ctx.query
    if (!token) {
        return ctx.body = { success: false, errorCode: 41064, message: "用户信息获取失败", data: null }
    }
    try {
        const { id } = key(token)
        const data = await db.findOne('user', { _id: id })
        if (data.length == 0) {
            ctx.body = { success: false, errorCode: 41064, message: "用户信息获取失败", data: null }
        } else {
            ctx.body = { success: true, errorCode: 20000, message: '用户信息获取成功', data: data[0] }
        }
    } catch (error) {
        return ctx.body = { success: false, errorCode: 41064, message: "令牌错误,无法授权", data: null }
    }
})

// 查询 分页
router.get('/list', async ctx => {
    const { page = 0, pageSize = 20, query, query2 } = ctx.request.query // request可省略
    let sort = {}, where = {}
    if (query || query2) { // status
        where.status = { $in: [query * 1, query2 * 1] }
    }
    const total = await db.total('user', where)
    const data = await db.find('user', { where, sort, skip: page * pageSize, limit: pageSize })
    ctx.body = { success: true, code: 20000, message: "数据查询成功", data, total }
})

// 新增
router.post('/save', async ctx => {
    const { name, loginKey, loginName, introduction, tel, address, position } = ctx.request.body;
    const data = await db.insert('user', { name, loginKey, loginName, introduction, tel, address, position, status: 0, time: Date.now() })
    ctx.body = { success: true, code: 20000, message: "数据新增成功", data }
})

// 修改
router.post('/modify', async ctx => {
    const { _id, name, loginKey, introduction, tel, address, position, status, logo, refuse } = ctx.request.body
    const data = await db.update('user', { _id }, { name, loginKey, introduction, tel, address, position, status, logo, refuse, time: Date.now() })
    ctx.body = { success: true, code: 20000, message: "数据修改成功", data }
})

// 删除
router.get('/delete', async ctx => {
    const { _id } = ctx.request.query
    const data = await db.delete('user', { _id })
    ctx.body = { success: true, code: 20000, message: "数据删除成功", data }
})

// 查询注册结果 // 店铺名称查重
router.get('/get-status', async ctx => {
    const { name } = ctx.request.query // request可省略
    const data = await db.findOne('user', { name })
    ctx.body = { success: true, code: 20000, message: "数据查询成功", data }
})

// 商户账号查重
router.get('/get-loginName', async ctx => {
    const { loginName } = ctx.request.query // request可省略
    const data = await db.findOne('user', { loginName })
    ctx.body = { success: true, code: 20000, message: "数据查询成功", data }
})

module.exports = router